﻿import { getCurrentTime } from './time_lib';

export function GetCurrentTime() {
    return getCurrentTime();
}

let pyodide;
let pyodideReady = false;
let nativefs;



export async function loadPyodideAndPackages() {

    if (pyodideReady) {
        return;
    }
    console.log("Pyodide 开始加载");
    pyodide = await loadPyodide();
    //await pyodide.loadPackage("micropip");
    //const micropip = pyodide.pyimport("micropip");

    //// 安装 pandas 和 numpy
    //await micropip.install("pandas");
    //await micropip.install("numpy");
    pyodideReady = true;
    console.log("Pyodide 已准备好");
    //console.log("Pyodide + Pandas/Numpy loaded!");
}

export async function writeFileToPyodide(filename, content) {
    await loadPyodideAndPackages();
    pyodide.FS.writeFile(filename, content);
}

export async function runPythonCode(code) {
    await loadPyodideAndPackages();
    return pyodide.runPython(code);
}

export async function initialize() {
    await loadPyodideAndPackages();
}

export async function copyToClipboard(text) {
    if (navigator.clipboard && window.isSecureContext) {
        // 现代浏览器，使用 Clipboard API
        return navigator.clipboard.writeText(text);
    } else {
        // 降级方案：使用 document.execCommand
        const textArea = document.createElement("textarea");
        textArea.value = text;
        textArea.style.position = "fixed";  // 避免滚动到不可见区域
        textArea.style.left = "-999999px";
        textArea.style.top = "-999999px";
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        return new Promise((resolve, reject) => {
            const successful = document.execCommand('copy');
            document.body.removeChild(textArea);
            if (successful) {
                resolve();
            } else {
                reject(new Error('复制失败'));
            }
        });
    }
}

export async function copyElementText(elementId) {
    const element = document.getElementById(elementId);
    if (element) {
        return window.copyToClipboard(element.innerText || element.textContent || '');
    }
    return Promise.reject(new Error('元素未找到'));
}

export async function convertToDm(db) {

    const dirHandle = await showDirectoryPicker();
    const permissionStatus = await dirHandle.requestPermission({
        mode: "readwrite",
    });

    if (permissionStatus !== "granted") {
        throw new Error("readwrite access to directory not granted");
    }
    await loadPyodideAndPackages();

    if (!isMounted("/mount_dir")) {
        await fetch("mysql_to_dm.py")
            .then(response => response.text())
            .then(text => {
                pyodide.FS.writeFile("/mysql_to_dm.py", text);
            });
        nativefs = await pyodide.mountNativeFS("/mount_dir", dirHandle);
    }


    let result = await runPythonCode(`
  import os
  import sys
  sys.path.append('/')
  from mysql_to_dm import generate_dm_script
  generate_dm_script('${db}', '/mount_dir')
`);
    document.getElementById("sqlResult").innerText = result;
    console.log(result);
    await nativefs.syncfs();
}

function isMounted(mountPath) {
    try {
        const { node } = pyodide.FS.lookupPath(mountPath, { follow_mount: false });
        return pyodide.FS.isMountpoint(node);
    } catch (e) {
        return false;
    }
}

//window.onload = async () => {
//    await loadPyodideAndPackages();
//};